#!/usr/bin/env ./script/runner
# author: matias
#
# Sends a given newsletter to active contacts.

require 'getoptlong'
require 'script/mass_email/mass_email_sender'

opts = GetoptLong.new(
  [ '--newsletter', '-n', GetoptLong::REQUIRED_ARGUMENT],
  [ '--no_test', GetoptLong::OPTIONAL_ARGUMENT]
)

testing = true
newsletter_id = nil

opts.each do |opt, arg|
  case opt
    when '--no_test':
      testing = false
    when '--newsletter'
      newsletter_id = arg.to_i
  end
end  

raise ArgumentError, "--newsletter option is required" if newsletter_id.nil?

if testing
  ActionMailer::Base.delivery_method = :test
  puts "[in TEST mode; no emails will actually be sent]\n" if 
      ActionMailer::Base.delivery_method == :test
end

sender = MassEmailSender.new(Newsletter.find(newsletter_id), true)
print "getting active contacts... "
sender.get_contacts!
puts "found #{sender.contacts.length} active"

puts "ready to send emails with subject '#{sender.newsletter.subject}'."
print "please type yes to continue: "
input = STDIN.readline
unless input.starts_with? 'yes'
  puts "you did not type 'yes'. quitting."
  exit
end

puts "here we go!"
sender.send_emails! do |msg|
  print msg
end

puts "\nall done: #{sender.success_count} successful, #{sender.error_count} errors, " +
     "#{sender.skipped_count} skipped."
